import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Tag, Table, Select, Card } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormSelect } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import {
  ActiveEmployee,
  getActiveCodeList,
  getActiveOrderList,
  getEmployeeListById,
  updateConfig,
  updateEmployee,
  pushConfig,
  createConfig,
  getEmployeeList,
} from './service';
import type { AddEmployeeItem, AddConfigItem, TableListItem, TableListPagination } from './data';
import { Image } from 'antd';
import { getWxConfigList } from '@/services/ant-design-pro/wechat';
import type { ColumnsType } from 'antd/es/table';
import CreateForm from './components/CreateForm';
import EmployeeConfigForm from './components/EmployeeConfig';
import { Link } from 'umi';

/**
 * 添加客服
 *
 * @param fields
 */

const handleEmployee = async (fields: AddEmployeeItem) => {
  const hide = message.loading('正在配置客服');
  try {
    await updateEmployee({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 添加配置
 *
 * @param fields
 */

const handleAdd = async (fields: AddConfigItem) => {
  const hide = message.loading('正在添加');
  try {
    await createConfig({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

interface EmployeeDataType {
  key: string;
  name: string;
  user_id: string;
  status: string;
  welcome: string;
}

interface InitCorpDataType {
  value: string;
  label: string;
}

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [configEmployeeModalVisible, handleConfigEmployeeModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */

  const [activeUserInitValue, setActiveUserInitValue] = useState<string>('');
  const [updateActiveVisible, handleUpdateActiveVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  /** 国际化配置 */

  const [employeeResult, setEmployeeResult] = useState({});
  const [activeOrder, setActiveOrder] = useState({});
  const [activeCode, setActiveCode] = useState({});
  const [corpIdConfig, setCorpIdConfig] = useState(CORP_ID);
  const [employeeListByConfigID, setEmployeeListByConfigID] = useState<EmployeeDataType[]>([]);

  const [initCorp, setInitCorp] = useState<InitCorpDataType[]>([]);

  useEffect(() => {
    // todo 获取企业微信配置列表
    setInitCorp([{ value: CORP_ID, label: '我的企业' }]);
    // 设置默认搜索条件
    setCorpIdConfig(CORP_ID);
  }, []);

  const employeeColumns: ColumnsType<EmployeeDataType> = [
    {
      title: '客服名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
      width: 120,
    },
    {
      title: '客服id',
      key: 'user_id',
      dataIndex: 'user_id',
      width: 300,
      render: (_, { user_id }) => (
        <>
          <Tag color={'volcano'} key={'user_id'}>
            {user_id}
          </Tag>
        </>
      ),
    },
    {
      title: '欢迎语',
      key: 'welcome',
      dataIndex: 'welcome',
      width: 200,
    },
    {
      title: '激活状态',
      key: 'status',
      dataIndex: 'status',
      render: (_, { status, user_id }) => (
        <>
          {status === '' ? (
            <Button
              onClick={() => {
                setActiveUserInitValue(user_id);
                handleUpdateActiveVisible(true);
              }}
            >
              未激活
            </Button>
          ) : (
            <Button
              onClick={() => {
                setActiveUserInitValue(user_id);
                handleUpdateActiveVisible(true);
              }}
            >
              已激活
            </Button>
          )}
        </>
      ),
    },
  ];

  const { Option } = Select;

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '配置描述',
      dataIndex: 'name',
      tip: '描述配置的详情',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              console.log('selectedRows', 'selectedRows');
              getEmployeeListById(entity.corpid, entity.id).then((res) => {
                const obj: EmployeeDataType[] = [];
                res.data.forEach((item) => {
                  obj.push({
                    key: item.Id + '',
                    name: item.name,
                    user_id: item.open_user_id,
                    status: item.status,
                    welcome: item.welcome,
                  });
                });

                setEmployeeListByConfigID(obj);
                setCurrentRow(entity);
                setShowDetail(true);
              });
            }}
          >
            {dom}
          </a>
        );
      },
      search: false,
    },
    {
      title: '联系方式',
      dataIndex: 'category',
      valueType: 'textarea',
      renderText: (val: string) => {
        if (val == '1') {
          return '单人';
        } else {
          return '多人';
        }
      },
      search: false,
    },
    {
      title: '触达类型',
      dataIndex: 'scene',
      valueType: 'textarea',
      renderText: (val: string) => {
        if (val == '1') {
          return '小程序';
        } else {
          return '二维码';
        }
      },
      search: false,
    },
    // {
    //   title: '小程序样式',
    //   dataIndex: 'style',
    //   valueType: 'textarea',
    //   search: false,
    // },
    {
      title: '渠道码',
      dataIndex: 'channel',
      valueType: 'textarea',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '企业id',
      dataIndex: 'corpid',
      valueType: 'textarea',
      copyable: true,
      ellipsis: true,
      initialValue: corpIdConfig,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }

        return (
          <Select placeholder="请选择一个要查询的企业" {...rest}>
            {initCorp.map((node) => (
              <Option key={node.value} value={node.value}>
                {node.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '配置码',
      dataIndex: 'config_id',
      valueType: 'textarea',
      copyable: true,
      ellipsis: true,
      // renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
      //   if (type === 'form') {
      //     return null;
      //   }
      //   return (
      //     <Select placeholder="请选择一个要查询的企业" {...rest}>
      //       {initCorp.map((node) => (
      //         <Option key={node.value} value={node.value}>
      //           {node.label}
      //         </Option>
      //       ))}
      //     </Select>
      //   );
      // },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        config: {
          text: '配置中',
          status: 'config',
        },
        deployed: {
          text: '已部署',
          status: 'deployed',
        },
      },
      search: false,
    },
    {
      title: '二维码',
      dataIndex: 'qr_code',
      render: (text) => {
        return (
          <div>
            <Image
              src={text?.toString()}
              width={100}
              height={100}
              fallback=""
            />
          </div>
        );
      },
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="subscribeAlert"
          onClick={() => {
            handleConfigEmployeeModalVisible(true);
            setCurrentRow(record);
          }}
        >
          客服配置
        </a>,
        <a
          key="config"
          onClick={async () => {
            const hide = message.loading('正在部署客服');
            try {
              if (record.config_id === '') {
                await pushConfig(record);
              } else {
                await updateConfig(record);
              }
              hide();
              message.success('部署成功');

              if (actionRef.current) {
                actionRef.current.reload();
              }

              return true;
            } catch (error) {
              hide();
              message.error('部署失败请重试！');
              return false;
            }
          }}
        >
          部署配置
        </a>,
      ],
    },
  ];

  // const UploaderInnerJSXElement = <div>这是放在uploader里面的元素，可以随意替换</div>;
  function urlencode(str: any) {
    const temp = (str + '').toString();

    return encodeURIComponent(temp)
      .replace(/!/g, '%21')
      .replace(/'/g, '%27')
      .replace(/\(/g, '%28')
      .replace(/\)/g, '%29')
      .replace(/\*/g, '%2A')
      .replace(/%20/g, ' ');
  }

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="配置详情"
        actionRef={actionRef}
        rowKey="id"
        search={{ labelWidth: 'auto' }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建配置
          </Button>,
        ]}
        request={(params) => getWxConfigList(params)}
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
      />

      {/* 新建配置 */}
      <CreateForm
        createModalVisible={createModalVisible}
        handleModalVisible={handleModalVisible}
        onSubmit={async (value) => {
          value.corp_id = corpIdConfig;
          const success = await handleAdd(value as AddConfigItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      />

      {/* 客服配置 */}
      <EmployeeConfigForm
        employeeResult={employeeResult}
        configEmployeeModalVisible={configEmployeeModalVisible}
        handleConfigEmployeeModalVisible={handleConfigEmployeeModalVisible}
        onSubmit={async (value) => {
          const params = {
            welcome_message: urlencode(value.welcome_message),
            employee_select: value.employee_select,
            contact_id: currentRow?.id,
            corp_id: corpIdConfig,
          };
          const success = await handleEmployee(params as AddEmployeeItem);
          if (success) {
            handleConfigEmployeeModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        request={async (params, options) => {
          const result = await getEmployeeList(params, options, corpIdConfig);
          const obj = {};
          result.data.forEach((item) => {
            obj[item.open_userid + ':' + item.name + ':' + item.userid] = item.name;
          });
          setEmployeeResult(obj);
          return result;
        }}
      />

      <ModalForm
        title="客服激活"
        width="400px"
        visible={updateActiveVisible}
        onVisibleChange={handleUpdateActiveVisible}
        onFinish={async (value) => {
          const hide = message.loading('正在激活客服...');
          try {
            await ActiveEmployee(value.code_select, activeUserInitValue, corpIdConfig);
            hide();
            message.success('激活成功');
            if (actionRef.current) {
              actionRef.current.reload();
            }
            return true;
          } catch (error) {
            hide();
            message.error('激活失败请重试！');
            return false;
          }
        }}
        initialValues={{}}
        request={async (params, options) => {
          setActiveCode({});
          const result = await getActiveOrderList(corpIdConfig, options);
          const obj = {};
          result.data.forEach((item) => {
            obj[item.order_id] = item.order_id;
          });
          setActiveOrder(obj);
          return result;
        }}
        modalProps={{ destroyOnClose: true }}
      >
        <ProFormSelect
          name="order_select"
          label="选择订单"
          valueEnum={activeOrder}
          placeholder="选择在企业微信后台中激活的订单"
          rules={[{ required: true, message: '需要选择一个订单!' }]}
          allowClear
          fieldProps={{
            onChange: (value) => {
              const result = getActiveCodeList(corpIdConfig, value);
              result.then((res) => {
                const obj = {};
                res.data.forEach((item) => {
                  obj[item.active_code] = item.active_code;
                });
                setActiveCode(obj);
              });
            },
          }}
        />

        <ProFormSelect
          name="code_select"
          label="激活码选择"
          valueEnum={activeCode}
          placeholder="选择一个激活码"
          allowClear
          rules={[{ required: true, message: '需要选择一个激活码!' }]}
        />
      </ModalForm>

      <Drawer
        width={800}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}

        <Link to={'/wechat/mp-config?config_id=' + currentRow?.config_id}>
          <Button>单独配置小程序样式:click</Button>
        </Link>

        <Table columns={employeeColumns} dataSource={employeeListByConfigID} />
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
